package com.njupt.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyUtil 
{
	private static final String slat = "&%5123***&&%%$$#@";
	
	public static String getTime()
	{
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		return sdf.format(new Date());
	}
	public static String encrypt(String dataStr) {
		try {
			dataStr = dataStr + slat;
			MessageDigest m = MessageDigest.getInstance("MD5");
			m.update(dataStr.getBytes("UTF8"));
			byte s[] = m.digest();
			String result = "";
			for (int i = 0; i < s.length; i++) {
				result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00).substring(6);
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}
	
	public static String getSha1(String str)
	{
	    if (null == str || 0 == str.length()){
	        return null;
	    }
	    char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
	            'a', 'b', 'c', 'd', 'e', 'f'};
	    try {
	        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
	        mdTemp.update(str.getBytes("UTF-8"));
	         
	        byte[] md = mdTemp.digest();
	        int j = md.length;
	        char[] buf = new char[j * 2];
	        int k = 0;
	        for (int i = 0; i < j; i++) {
	            byte byte0 = md[i];
	            buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
	            buf[k++] = hexDigits[byte0 & 0xf];
	        }
	        return new String(buf);
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	    }
	    return "";
	}
	
	
	
	public static String encode(String s, int key)
	{
		if(s==null) return null;
		  char str[]=s.toCharArray();
		  for(int i=0;i<str.length;i++)
		  {
			  if(str[i]>='A'&&str[i]<='Z')
			  {
				  int key1=key%26;
				  int index=(str[i]-'A'+26+key1)%26;
				  str[i]=(char)(index+'A');
			  }
			  else if(str[i]>='a'&&str[i]<='z')
			  {
				  int key1=key%26;
				  int index=(str[i]-'a'+26+key1)%26;
				  str[i]=(char)(index+'a');
			  }
			  else if(str[i]>='0'&&str[i]<='9')
			  {
				  int key1=key%10;
				  int index=(str[i]-'0'+10+key1)%10;
				  str[i]=(char)(index+'0');
			  }
		  }
		  return new String(str);
	}

	public static void main(String[] args)
	{
		String s="123";
		System.out.println(getSha1(s));
	}
}
